import { AsyncStorage } from 'react-native';
const STORAGE_KEY = "STORAGE_KEY_message";
export default {
    namespace: 'message',
    state: {
        loading: false,
        list: [],
    },
    reducers: {
        save(state, { payload }) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        *saveToStorage({ payload }, { call }) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload));
        },
        *restoreFromStorage({ payload }, { call, put, select }) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: Object.assign({}, JSON.parse(data))
            });
        },
        *clear({ payload }, { put }) {
        },
        *newMessage({ payload }, { put, select }) {
            const message = yield select(state => state.message);
            message.list.push(payload);
            yield put({
                type: 'save',
                payload: Object.assign({}, message)
            });
            yield put({
                type: 'saveMessage'
            });
        },
        *readMessage({ payload }, { put, select }) {
            const message = yield select(state => state.message);
            message.list.splice(message.list.indexOf(payload), 1);
            yield put({
                type: 'save',
                payload: Object.assign({}, message)
            });
            yield put({
                type: 'saveToStorage',
                payload: Object.assign({}, message)
            });
        },
        *readMessageFromUser({ payload }, { put, select }) {
            const receiver = payload.receiver;
            let message = yield select(state => state.message);
            message.list = message.list.filter((m) => m && m.username !== receiver);
            yield put({
                type: 'save',
                payload: Object.assign({}, message)
            });
            yield put({
                type: 'saveToStorage',
                payload: Object.assign({}, message)
            });
        },
        *saveMessage({ payoad }, { put, select }) {
            const message = yield select(state => state.message);
            yield put({
                type: 'saveToStorage',
                payload: Object.assign({}, message)
            });
        },
        *restoreMessage({ payload }, { put }) {
            yield put({
                type: 'restoreFromStorage',
                payload: {}
            });
        }
    },
    subscriptions: {
        setup({ dispatch }) {
            dispatch({
                type: 'restoreMessage'
            });
        }
    },
};
